<template>
	<div>
		<el-table
			:data="tbdata"
			style="width: 100%"
			stripe
			highlight-current-row
			height="600"
			empty-text="暂时没有数据"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="55" fixed="left"></el-table-column>
			<el-table-column label="学生学号" prop="id" width="120" sortable></el-table-column>
			<el-table-column label="学生姓名" prop="name" width="120" sortable align="center"></el-table-column>
			<el-table-column label="年龄" prop="birthday" width="120" sortable align="center">
				<template slot-scope="scope">
					{{ scope.row.birthday | ageFilter }}
				</template>
			</el-table-column>
			<el-table-column label="院系" prop="department" width="150" :filters="departmentFilters" :filter-method="(value,row)=>{return row.department==value}" align="center"></el-table-column>
			<el-table-column label="班级" prop="class" width="150" sortable align="center"></el-table-column>
			<el-table-column label="性别" prop="sex" :filters="[{value:'男',text:'男'},{value:'女',text:'女'}]" :filter-method="(value,row)=>{return row.sex==value}" width="120" align="center"></el-table-column>
			<el-table-column label="电话" prop="telephone" width="180"></el-table-column>
			<el-table-column align="right" fixed="right" width="250">
				<template slot="header" slot-scope="scope">
					<el-select v-model="searchType" placeholder="请选择" size="mini" style="width: 90px;padding: 0;">
					    <el-option value="学号"></el-option>
						<el-option value="姓名"></el-option>
						<el-option value="年龄"></el-option>
					</el-select>
					<el-input v-model="search" size="mini" placeholder="输入关键字搜索" style="padding: 0; width: 120px;" />
				</template>
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
					<el-button size="mini" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index, scope.row)"></el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog :title="dialogType == 'create' ? '创建学生' : '编辑学生'" :visible.sync="dialogFormVisible">
			<el-form :model="form" v-if="form">
				<el-form-item label="学生编号" :label-width="formLabelWidth">
					<el-input v-model="form.id" autocomplete="off" :disabled="dialogType == 'edit'"></el-input>
				</el-form-item>
				<el-form-item label="学生姓名" :label-width="formLabelWidth"><el-input v-model="form.name" autocomplete="off"></el-input></el-form-item>
				<el-form-item label="学生密码" :label-width="formLabelWidth">
					<el-input v-model="form.password" type="password" autocomplete="off" show-password></el-input>
				</el-form-item>
				<el-form-item label="学生性别" :label-width="formLabelWidth">
					<el-select v-model="form.sex" placeholder="请选择性别">
						<el-option label="男" value="男"></el-option>
						<el-option label="女" value="女"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="学生电话" :label-width="formLabelWidth"><el-input v-model="form.telephone" autocomplete="off"></el-input></el-form-item>
				<el-form-item label="学生生日" :label-width="formLabelWidth">
					<el-date-picker v-model="form.birthday" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
				</el-form-item>
				<el-form-item label="学生系别" :label-width="formLabelWidth">
					<el-select v-model="form.department" placeholder="请选择院系">
						<el-option :label="item.department" :value="item.department" v-for="(item, index) in $store.state.departments" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="学生班级" :label-width="formLabelWidth">
					<el-select v-model="form.class" placeholder="请选择班级" :disabled="!schoolclass">
						<el-option :label="item" :value="item" v-for="(item, index) in schoolclass" :key="index"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button
					@click="
						dialogFormVisible = false;
						form = null;
					"
				>
					取 消
				</el-button>
				<el-button type="primary" @click="formConfirm">{{ dialogType == 'create' ? '创建' : '确定' }}</el-button>
			</div>
		</el-dialog>
		<el-button icon="el-icon-circle-plus-outline" type="primary" @click="createStudent">新建学生</el-button>
		<el-button icon="el-icon-refresh-right" type="infor" @click="getStudents"></el-button>
		<el-button icon="el-icon-delete" type="danger" @click="batchDelete"></el-button>
	</div>
</template>

<script>
export default {
	data() {
		return {
			tableData: [],
			search: '',
			dialogFormVisible: false,
			form: null,
			formLabelWidth: '120px',
			dialogType: 'edit',
			selectedArr: [],
			searchType:'学号'
		};
	},
	mounted: function() {
		this.getStudents();
	},
	filters: {
		/**
		 * 根据出生日期计算年龄
		 *
		 * @param {Object} value 出生日期
		 */
		ageFilter: function(value) {
			if (!value) return;
			let b = new Date(value);
			let d = new Date();
			return d.getFullYear() - b.getFullYear() - (d.getMonth() < b.getMonth() || (d.getMonth() == b.getMonth() && d.getDate() < b.getDate()) ? 1 : 0);
		}
	},
	methods: {
		/**
		 * 获取所有学生信息
		 */
		getStudents() {
			let that = this;
			that.tableData = [];
			that.axios
				.get(that.$store.state.serverHost + '/student/getStudents/')
				.then(res => {
					let reg = new RegExp("'", 'g');
					for (let i in res.data) {
						let data = JSON.parse(res.data[i].replace('"', '').replace(reg, '"'));
						that.tableData.push(data);
					}
					that.$store.commit('updataStudents', that.tableData);
				})
				.catch(e => {
					console.log(e);
					that.$message.error('获取数据失败');
				});
		},
		/**
		 * 点击编辑按钮触发,格式化数据，打开表单
		 *
		 * @param {Number} index 数据中的角标
		 * @param {Object} row 数据对象
		 */
		handleEdit(index, row) {
			console.log(index, row);
			let that = this;
			if (that.dialogFormVisible) return;
			if (that.dialogType != 'edit') that.dialogType = 'edit';
			that.form = row;
			that.dialogFormVisible = true;
		},
		/**
		 * 点击删除按钮触发
		 *
		 * @param {Number} index 数据中的角标
		 * @param {Object} row 数据对象
		 */
		handleDelete(index, row) {
			console.log(index, row);
			let that = this;
			that.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				that.deleteStudent(
					row.id,
					() => {},
					() => {
						that.$message.error('删除失败');
						return;
					}
				);

				that.$message({
					type: 'success',
					message: '删除成功!'
				});
				setTimeout(() => {
					that.getStudents();
				}, 1000);
			});
		},
		/**
		 * 删除一个学生
		 *
		 * @param {Number} id	学生id
		 * @param {Function} success	删除成功回调
		 * @param {Function} fail	删除失败回调
		 */
		deleteStudent(id, success, fail) {
			let that = this;
			that.axios
				.post(that.$store.state.serverHost + '/student/deleteStudent/', {
					id: id
				})
				.then(res => {
					console.log(res);
					if (res.data != '删除成功' && fail) fail();
					if (success) success();
				})
				.catch(e => {
					console.log(e);
					if (fail) fail();
				});
		},
		/**
		 * 表单点击提交按钮触发
		 */
		formConfirm() {
			let that = this;
			if (!that.form) return;
			for (let key in that.form) {
				if (!that.form[key]) {
					that.$message.error(key + '不能为空');
					return;
				}
			}
			if (that.dialogType == 'create') {
				that.axios
					.post(that.$store.state.serverHost + '/student/register/', that.form)
					.then(res => {
						console.log(res);
						if(res.data==="注册成功") that.$message.success('创建成功');
						else that.$message.error(res.data)
						that.getStudents();
					})
					.catch(e => {
						console.log(e);
					});
			} else {
				console.log('修改信息');
				that.axios
					.post(that.$store.state.serverHost + '/student/changeStudent/', that.form)
					.then(res => {
						if (res.data != '修改失败') that.$message.success('修改成功');
						setTimeout(() => {
							that.getStudents();
						}, 1000);
					})
					.catch(e => {
						console.log(e);
					});
			}
			that.dialogFormVisible = false;
			that.form = null;
		},
		/**
		 * 创建学生，格式化数据，打开表单
		 */
		createStudent() {
			let that = this;
			if (that.dialogFormVisible) return;
			if (that.dialogType != 'create') that.dialogType = 'create';
			that.form = {
				id: '',
				name: '',
				birthday: '',
				sex: '',
				department: '',
				class: '',
				telephone: '',
				password: ''
			};
			that.dialogFormVisible = true;
		},
		/**
		 * 点击批量删除按钮触发
		 */
		batchDelete() {
			let that = this;
			if(that.selectedArr.length<1) return
			that.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				for (let i in that.selectedArr) {
					that.deleteStudent(that.selectedArr[i].id);
				}
				that.$message({
					type: 'success',
					message: '删除成功!'
				});
				setTimeout(() => {
					that.getStudents();
				}, 1000);
			});
		},
		/**
		 * 选中一项时触发
		 *
		 * @param {Array} value 包含被选中对象的数组
		 */
		handleSelectionChange(value) {
			this.selectedArr = value;
		}
	},
	computed: {
		/**
		 * @return 学院中的班级数组
		 */
		schoolclass() {
			if (this.form.department) {
				for (let item in this.$store.state.departments) {
					if (this.form.department == this.$store.state.departments[item].department) {
						return this.$store.state.departments[item].classes;
					}
				}
			}
			return null;
		},
		/**
		 * 表格中展示的数据
		 */
		tbdata(){
			let that = this
			let ageFilter = that.$options.filters['ageFilter']
			return that.tableData.filter((data) => {
				if(!that.search) return true
				switch(that.searchType){
					case "姓名":
						return JSON.stringify(data.name).includes(that.search)
					case "年龄":
						return JSON.stringify(ageFilter(data.birthday)).includes(that.search)
					default:
						return JSON.stringify(data.id).includes(that.search)
				}
			})
		},
		departmentFilters(){
			let a = []
			for(let i in this.$store.state.departments){
				a.push({value:this.$store.state.departments[i].department,text:this.$store.state.departments[i].department})
			}
			return a
		}
	}
};
</script>

<style scoped></style>
